import os

from PyQt4 import QtCore
from limber.documents._filewrapper import FileWrapperDocument

from limber.componentparser import ComponentInfos


class BaseTextDocument(FileWrapperDocument):
    '''Simple Document class that can handle text files.'''

    title_changed = QtCore.pyqtSignal((),(unicode,), name='titleChanged')

    def __init__(self, parent=None, path=None, mode=None):
        super(BaseTextDocument, self).__init__(parent, path, mode)

        if path is not None:
            self.set_title(os.path.basename(path))

    def data(self, query=None, format=None):
        '''Return the data specified by *query* using *format*.'''

        if query is None:
            query = BaseTextDocumentQuery(0, -1)
        if format is None:
            format = str

        cur_pos = self.tell()
        self.seek(query.from_pos)

        if query.to_pos == -1:
            data = self.read()
        else:
            data = self.read(query.to_pos - query.from_pos)

        self.seek(cur_pos)

        return format(data)

    def set_data(self, data, query=None, format=None):
        '''Set the document's *data* using *query* and *format*.'''

        if query is None:
            query = BaseTextDocumentQuery(0, -1)

        if format is None:
            format = str

        cur_pos = self.tell()
        self.seek(query.from_pos)

        if query.to_pos == -1:
            data_to_write = format(data)
        else:
            data_to_write = format(data)[:query.to_pos - query.from_pos]
        self.write(data_to_write)

        if query.truncate:
            atm_pos = self.tell()
            self.truncate(atm_pos + 1)

        self.seek(cur_pos)


class BaseTextDocumentQuery(object):

    def __init__(self, from_pos=0, to_pos=-1, truncate=False):
        self.from_pos = from_pos
        self.to_pos = to_pos
        self.truncate = truncate


INFOS_DICT = {
    'name' : 'basetextdocument',
    'full_name' : 'Plain Text Document',
    'class_name' : 'BaseTextDocument',
    'directory' : '../Widgets',
    'filename' : 'basetextdocument.py',
    'version' : '0.1.0',
    'short_description' : 'A simple text document.',
    'author' : 'Giacomo Alzetta',
    'interface' : 'document',
    'abilities' : 'TEXT:PLAIN_TEXT',
    }

COMPONENT_FILE_CONTENT = '''\
name = %(name)s
full_name = %(full_name)s
class_name = %(class_name)s
directory = %(directory)s
filename = %(filename)s
version = %(version)s
short_description = %(short_description)s
author = %(author)s
interface = %(interface)s
abilities = %(abilities)s
''' % INFOS_DICT

_better_infos = dict(INFOS_DICT)
_better_infos['abilities'] = INFOS_DICT['abilities'].split(':')

INFOS = ComponentInfos(**_better_infos)

del _better_infos
